package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.ProductFeignClient;
import cn.com.dcsgo.enums.CouponRangeType;
import cn.com.dcsgo.mapper.CouponRangeMapper;
import cn.com.dcsgo.model.activity.CouponInfo;
import cn.com.dcsgo.mapper.CouponInfoMapper;
import cn.com.dcsgo.model.activity.CouponRange;
import cn.com.dcsgo.model.product.Category;
import cn.com.dcsgo.model.product.SkuInfo;
import cn.com.dcsgo.service.CouponInfoService;
import cn.com.dcsgo.vo.activity.CouponRuleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠券信息 服务实现类
 * </p>
 *
 * @author Dcsgo
 * @since 2025-04-19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements CouponInfoService {
    private final CouponRangeMapper couponRangeMapper;
    private final ProductFeignClient productFeignClient;

    @Override
    public IPage<CouponInfo> getPageList(Page<CouponInfo> pageParam) {
        //需要封装给前端用的：优惠券类型、范围
        IPage<CouponInfo> couponInfoPage = baseMapper.selectPage(pageParam, null);
        List<CouponInfo> couponInfoList = couponInfoPage.getRecords();
        couponInfoList.forEach(couponInfo -> {
            couponInfo.setCouponTypeString(couponInfo.getCouponType().getComment());
            //范围可能为null
            if (couponInfo.getRangeType() != null) {
                couponInfo.setRangeTypeString(couponInfo.getRangeType().getComment());
            }
        });
        return couponInfoPage;
    }

    @Override
    public CouponInfo getCouponInfo(Long id) {
        //需要封装给前端用的：优惠券类型、范围
        CouponInfo couponInfo = baseMapper.selectById(id);
        couponInfo.setCouponTypeString(couponInfo.getCouponType().getComment());
        if (couponInfo.getRangeType() != null) {
            couponInfo.setRangeTypeString(couponInfo.getRangeType().getComment());
        }
        return couponInfo;
    }

    @Override
    public Map<String, List<? extends Serializable>> findCouponRuleList(Long id) {
        Map<String, List<? extends Serializable>> result = new HashMap<>();
        CouponInfo couponInfo = baseMapper.selectById(id);
        if (couponInfo == null) {
            return result;
        }
        //通过coupon_range查询优惠券规则
        //range_type 为 sku 则 coupon_range.range_id与skuId关联
        //range_type 为 category 则 coupon_range.range_id与 categoryId关联
        //Map中封装相应信息即可
        List<CouponRange> couponRangeList = couponRangeMapper.selectList(
                new LambdaQueryWrapper<CouponRange>().eq(CouponRange::getCouponId, id)
        );
        if (CollectionUtils.isEmpty(couponRangeList)) {
            return result;
        }
        List<Long> rangeIdList = couponRangeList.stream().map(CouponRange::getRangeId).collect(Collectors.toList());
        //规则类型为 sku 封装 sku 信息
        if (couponInfo.getRangeType().equals(CouponRangeType.SKU)) {
            List<SkuInfo> skuInfoList = productFeignClient.getSkuInfoByIds(rangeIdList);
            result.put("skuInfoList", skuInfoList);
        } else if (couponInfo.getRangeType().equals(CouponRangeType.CATEGORY)) {
            //规则类型为 category 封装 category 信息
            List<Category> categoryList = productFeignClient.getCategoryByIds(rangeIdList);
            result.put("categoryList", categoryList);
        }
        return result;
    }

    @Override
    public void save(CouponRuleVo couponRuleVo) {
        //添加新的优惠券规则需要将原先的优惠券规则先删除掉
        couponRangeMapper.delete(
                new LambdaQueryWrapper<CouponRange>().eq(CouponRange::getCouponId, couponRuleVo.getCouponId())
        );
        //更新优惠券基本信息
        CouponInfo couponInfo = baseMapper.selectById(couponRuleVo.getCouponId());
        couponInfo.setRangeType(couponRuleVo.getRangeType());
        couponInfo.setConditionAmount(couponRuleVo.getConditionAmount());
        couponInfo.setAmount(couponRuleVo.getAmount());
        couponInfo.setConditionAmount(couponRuleVo.getConditionAmount());
        couponInfo.setRangeDesc(couponRuleVo.getRangeDesc());
        this.updateById(couponInfo);

        //设置优惠券规则集合中各个元素关联优惠券的id并保存到coupon_range表中
        couponRuleVo.getCouponRangeList().forEach(couponRange -> {
            couponRange.setCouponId(couponInfo.getId());
            couponRangeMapper.insert(couponRange);
        });
    }

    @Override
    public List<CouponInfo> findCouponRuleList(Long skuId, Long userId) {
        SkuInfo skuInfo = productFeignClient.getSkuInfoById(skuId);
        // 不存在这个 skuId 自接返回空列表
        if (skuInfo == null) {
            return new ArrayList<>(0);
        }
        // 根据 skuId 分类id userId 查询优惠券信息
        return baseMapper.selectBySkuIdAndCategoryAndUserId(skuId, skuInfo.getCategoryId(), userId);
    }
}
